package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author gsy
 * @date 2021年09月06日19:50
 * Description
 */
@RestController
@RequestMapping("/api/user/passport")
public class LoginCotroller {
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate redisTemplate;
    //登录
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){
        //判断账号和密码是否正确
        if (userInfo==null|| StringUtils.isEmpty(userInfo.getLoginName())||
        StringUtils.isEmpty(userInfo.getPasswd()==null)){
            return Result.fail().message("请输入账号和密码");
        }
        userInfo = userInfoService.login(userInfo);
        if (userInfo!=null){
            //用户存在
            //将用户id存入redis缓存中
            String token = UUID.randomUUID().toString().replaceAll("-","");
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+token,userInfo.getId().toString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            //回显昵称,将token传给前端
            Map map = new HashMap();
            map.put("token",token);
            map.put("nickName",userInfo.getNickName());
            return Result.ok(map);
        }else {
            return Result.fail().message("账号或密码不正确");
        }
    }

}
